﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Mortgage.DAL.Entity;
using Mortgage.DAL;


namespace Mortgage.Srv
{
    public interface IConfigSrv
    {
        List<tzConfig> GetAll(string code);
        tzConfig GetById(int id);
        int Insert(tzConfig insObj);
        int Update(tzConfig newsObj);
        int Delete(tzConfig delObje);
    }


    class ConfigSrv : IConfigSrv
    {

        private MortgageDataContext dataContext;

        public ConfigSrv()
        {
            dataContext = new MortgageDataContext();

        }


        public List<tzConfig> GetAll(string code)
        {
            List<tzConfig> result;
            result = dataContext.tzConfigs.Where(z => z.Code == code && z.IsDelete == false ).OrderBy(m => m.SortOrder).ToList();
            return result;
        }

        public tzConfig GetById(int id)
        {
            tzConfig result = dataContext.tzConfigs.Where(a => a.ID == id && a.IsDelete == false).FirstOrDefault();
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="insObj"></param>
        /// <returns>
        /// 0: success
        /// other: error code
        /// </returns>
        public int Insert(tzConfig insObj)
        {
            dataContext.tzConfigs.InsertOnSubmit(insObj);
            dataContext.SubmitChanges();
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newsObj"></param>
        /// <returns>
        /// 0: success
        /// 1: No find update object
        /// other: error code
        /// </returns>
        public int Update(tzConfig newsObj)
        {
            tzConfig entity = dataContext.tzConfigs.Where(a => a.ID == newsObj.ID).FirstOrDefault();
            if (entity == null) return 1;


            entity.Code = newsObj.Code;
            entity.Description = newsObj.Description;
            entity.Value = newsObj.Value;
            entity.SortOrder = newsObj.SortOrder;

            dataContext.SubmitChanges();
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="delObje"></param>
        /// <returns>
        /// 0: succcessful
        /// 1: No find delete object
        /// other: error code
        /// </returns>
        public int Delete(tzConfig delObje)
        {
            tzConfig entity = dataContext.tzConfigs.Where(a => a.ID == delObje.ID).FirstOrDefault();
            if (entity == null) return 1;

            entity.IsDelete = true;
            dataContext.SubmitChanges();

            return 0;
        }

    }
}
